package com.zzzzzz.app.account.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.app.account.NoSuchRoleException;
import com.zzzzzz.app.account.dao.RoleDao;
import com.zzzzzz.app.account.model.po.Role;
import com.zzzzzz.core.dao.search.SearchContainer;
import com.zzzzzz.core.exception.SystemException;

@Service
public class RoleManager {

	@Resource
	private RoleDao roleDao;

	@Resource
	private UserRoleManager userRoleManager;

	public Role add(Role role) throws Exception {
		return roleDao.add(role);
	}

	public void edit(Role role) throws SystemException {
		roleDao.edit(role);
	}

	@Transactional(rollbackFor = SystemException.class)
	public void delete(Long roleId) throws SystemException {
		userRoleManager.deleteByRoleId(roleId);
		roleDao.delete(roleId);
	}

	public Role findById(Long roleId) throws NoSuchRoleException, SystemException {
		return roleDao.findById(roleId);
	}
	
	public int findALLCount() throws SystemException {
		return roleDao.findALLCount();
	}

	public List<Role> findRoleList(int start, int offset) throws SystemException {
		return roleDao.findRoleList(start, offset);
	}

	public SearchContainer findRoleList(int cur, String actionPrefixURL) throws SystemException {
		return findRoleList(cur, actionPrefixURL, SearchContainer.DEFAULT_ITEMS_PER_PAGE, SearchContainer.DEFAULT_NUM_DISPLAY_PAGES, SearchContainer.DEFAULT_NUM_EDGE_PAGES);
	}
	
	public SearchContainer findRoleList(int cur, String actionPrefixURL, int offset, int numDisplayPages, int numEdgePages) throws SystemException {
		int total = findALLCount();
		int start = calculateStart(cur, offset, total);
		List<Role> roleList = findRoleList(start, offset);
		SearchContainer searchContainer = new SearchContainer(roleList, total, cur, actionPrefixURL, offset, numDisplayPages, numEdgePages);
		return searchContainer;
	}
	
	private int calculateStart(int cur, int offset, int total) {
		if(total == 0) {
			cur = 1;
		}else {
			cur = Math.min(cur, (int) Math.ceil((double) total/offset));
		}
		cur = Math.max(cur, 1);
		int start = (cur - 1) * offset;
		return start;
	}
}
